package com.example.zbh.dsliao.ui.activty;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.Html;
import android.text.TextWatcher;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.easemob.EMCallBack;
import com.easemob.EMEventListener;
import com.easemob.EMNotifierEvent;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMConversation;
import com.easemob.chat.EMGroup;
import com.easemob.chat.EMGroupManager;
import com.easemob.chat.EMMessage;
import com.easemob.chat.NormalFileMessageBody;
import com.easemob.chat.TextMessageBody;
import com.easemob.chat.VideoMessageBody;
import com.easemob.exceptions.EaseMobException;
import com.easemob.util.FileUtils;
import com.easemob.util.PathUtil;
import com.example.zbh.dsliao.R;
import com.example.zbh.dsliao.constant.Constant;
import com.example.zbh.dsliao.ui.adapter.FaceAdapter;
import com.example.zbh.dsliao.ui.adapter.GroupChatAdapter;
import com.example.zbh.dsliao.utils.DliaoUtils;
import com.example.zbh.dsliao.utils.FindSongs;
import com.example.zbh.dsliao.utils.PreferenceHelper;
import com.example.zbh.dsliao.view.FancyIndexer;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 群的聊天界面
 */
public class GroupChatActivity extends BaseActivity implements View.OnClickListener, EMEventListener, View.OnTouchListener, FaceAdapter.OnRecyclerItemClickListener, GroupChatAdapter.OnVoiceClickListener, GroupChatAdapter.OnItemChatOneLongClickListener, GroupChatAdapter.OnFileClickListener, GroupChatAdapter.OnShowVideoClickListener {
    private ListView listView;
    private String groupName = null;
    private EMConversation conversation;
    private EditText input_text;
    private Button send, add_contact, speak;
    private String text;
    private GroupChatAdapter adapter;
    private ImageView plus, group_image, face, voice;
    private Handler handler;
    private String currentName = null;
    private List<EMMessage> groupMessage = new ArrayList<>();
    private TextView add_list_friends, picture_tv, camera_tv, file_tv, voice_tv, video_phone_tv,
            video_tv, location_tv;
    private LinearLayout back, chatLin, lin_backG;
    private RecyclerView recyclerView;
    private GridLayoutManager manager;
    private FaceAdapter faceAdapter;
    private boolean isChatLin = false;
    private boolean isFace = true;//判断表情按钮
    private boolean isVoice = true;//判断语音按钮
    private File cameraFile;//相册文件
    private MediaRecorder mediaRecorder;//录音
    private MediaPlayer player;
    private String backGroundType;

    //语音文件夹
    private File diaoFile;


    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            refresh();
        }
    };

    private void refresh() {
        conversation = EMChatManager.getInstance().getConversation(groupName);
        groupMessage = conversation.getAllMessages();
        adapter.addData(groupMessage, currentName);
        listView.setSelection(groupMessage.size());

    }

    @Override
    protected int getLayOut() {
        return R.layout.activity_chat;
    }

    @Override
    protected void initView() {
        lin_backG = findeView(R.id.lin_backG);
        listView = findeView(R.id.listView);
        input_text = findeView(R.id.input_text);
        send = findeView(R.id.send);
        plus = findeView(R.id.plus);
        add_list_friends = findeView(R.id.add_list_friends);
        back = findeView(R.id.back);
        group_image = findeView(R.id.group_image);
        add_contact = findeView(R.id.add_contact);
        plus = findeView(R.id.plus);
        face = findeView(R.id.face);
        recyclerView = findeView(R.id.recyclerView);
        chatLin = findeView(R.id.chatLin);
        picture_tv = findeView(R.id.picture_tv);
        camera_tv = findeView(R.id.camera_tv);
        voice = findeView(R.id.voice);
        speak = findeView(R.id.speak);
        file_tv = findeView(R.id.file_tv);
        video_tv = findeView(R.id.video_tv);
        voice_tv = findeView(R.id.voice_tv);
        video_phone_tv = findeView(R.id.video_phone_tv);
        video_tv = findeView(R.id.video_tv);
        location_tv = findeView(R.id.location_tv);
    }

    private TextWatcher watcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            if (s.length() == 0) {
                plus.setVisibility(View.VISIBLE);
                send.setVisibility(View.GONE);
            } else {
                plus.setVisibility(View.GONE);
                send.setVisibility(View.VISIBLE);
            }

        }
    };

    @Override
    protected void initData() {
        backGroundType = PreferenceHelper.getInstance().getCurrentuserBackground(EMChatManager.getInstance().getCurrentUser());
        setBackGround();

        groupName = getIntent().getStringExtra(Constant.GROUPUSERID);
        String name = getIntent().getStringExtra(Constant.GROUPNAME);
        handler = new Handler();
        adapter = new GroupChatAdapter(this);
        send.setOnClickListener(this);
        add_contact.setVisibility(View.GONE);
        group_image.setBackgroundResource(R.drawable.dl_to_group_details_normal);
        group_image.setOnClickListener(this);
        input_text.addTextChangedListener(watcher);
        input_text.setOnTouchListener(this);
        add_list_friends.setText( name);
        conversation = EMChatManager.getInstance().getConversation(groupName);
        currentName = conversation.getUserName();
        groupMessage = conversation.getAllMessages();
        back.setOnClickListener(this);
        plus.setOnClickListener(this);
        picture_tv.setOnClickListener(this);
        camera_tv.setOnClickListener(this);
        voice.setOnClickListener(this);
        speak.setOnTouchListener(this);
        face.setOnClickListener(this);
        file_tv.setOnClickListener(this);
        video_tv.setOnClickListener(this);
        voice_tv.setVisibility(View.INVISIBLE);
        video_phone_tv.setVisibility(View.INVISIBLE);
        location_tv.setOnClickListener(this);
        listView.setAdapter(adapter);
        adapter.addData(groupMessage, currentName);
        adapter.setOnVoiceClickListener(this);
        adapter.setOnItemChatOneLongClickListener(this);
        adapter.setOnFileClickListener(this);
        adapter.setOnShowVideoClickListener(this);
        listView.setSelection(groupMessage.size());
        manager = new GridLayoutManager(this, 3, LinearLayoutManager.HORIZONTAL, false);
        recyclerView.setLayoutManager(manager);
        faceAdapter = new FaceAdapter();
        faceAdapter.addData(Constant.faces);
        recyclerView.setAdapter(faceAdapter);
        faceAdapter.setOnRecyclerItemClickListener(this);
        EMChatManager.getInstance().registerEventListener(
                this,
                new EMNotifierEvent.Event[]{EMNotifierEvent.Event.EventNewMessage,
                        EMNotifierEvent.Event.EventOfflineMessage, EMNotifierEvent.Event.EventDeliveryAck,
                        EMNotifierEvent.Event.EventReadAck});
    }

    private void setBackGround() {

        if (backGroundType != null){
            switch (backGroundType){
                case Constant.GIRL_ONE:
                    setBackGroundResource(Constant.GIRL_ONE_ID);
                    break;
                case Constant.GIRL_TWO:
                    setBackGroundResource(Constant.GIRL_TWO_ID);
                    break;
                case Constant.GIRL_THREE:
                    setBackGroundResource(Constant.GIRL_THREE_ID);
                    break;
                case Constant.JOURNEY_ONE:
                    setBackGroundResource(Constant.JOURNEY_ONE_ID);
                    break;
                case Constant.JOURNEY_TWO:
                    setBackGroundResource(Constant.JOURNEY_TWO_ID);
                    break;
                case Constant.JOURNET_THREE:
                    setBackGroundResource(Constant.JOURNET_THREE_ID);
                    break;
                case Constant.FRIEND:
                    setBackGroundResource(Constant.FRIEND_ID);
                    break;
                case Constant.BOY_ONE:
                    setBackGroundResource(Constant.BOY_ONE_ID);
                    break;
                case Constant.BOY_TWO:
                    setBackGroundResource(Constant.BOY_TWO_ID);
                    break;
            }
        }
    }
    //设置聊天背景的id
    private void setBackGroundResource(int id) {
        lin_backG.setBackgroundResource(id);



    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.send:
                sendTxtMessage();
                input_text.setText("");
                handler.postDelayed(runnable, 200);
                break;
            case R.id.back:
                finish();
                break;
            case R.id.group_image:
                Log.i("hjkhakhfdjkahfk", "跳转");
                Intent intent = new Intent();
                intent.putExtra(Constant.GROUPUSERID, groupName);
                intent.setClass(this, GroupDetailsActivity.class);
                startActivityForResult(intent, 1000);
                break;
            case R.id.plus:
                clickPlus();
                break;
            case R.id.face:
                clickFace();
                break;
            case R.id.picture_tv:
                selectPicFromLocal();
                break;
            case R.id.camera_tv:
                selectPicFromCamera();
                break;
            case R.id.voice:
                clickVoice();
                break;
            case R.id.file_tv:
                selectFileFromLocal();
                break;
            case R.id.video_tv:
                ClickVideoTv();
                break;
            case R.id.location_tv:
                clicklocation_tv();
                break;
        }
    }

    /**
     * 位置
     * **/
    private void clicklocation_tv() {
        Intent intent = new Intent(this, LocationActivity.class);
        startActivityForResult(intent, 520);
    }

    //语音
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        switch (v.getId()) {
            case R.id.input_text:
                chatLin.setVisibility(View.GONE);
                face.setImageResource(R.drawable.face);
                recyclerView.setVisibility(View.GONE);
                Log.i("sdadasdsadas", ">>>>>>>>");
                break;
            case R.id.speak:
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        startRecording();
                        break;
                    case MotionEvent.ACTION_UP:
                        stopRecording();
                        break;
                }
                break;
        }
        return false;
    }

    //语音播放
    @Override
    public void OnVoiceClick(String name) {
        startPlaying(name);
    }

    //下载文件
    @Override
    public void onFileClick(EMMessage message) {
        NormalFileMessageBody fileMessageBody = (NormalFileMessageBody) message.getBody();
        String filePath = fileMessageBody.getLocalUrl();
        File file = new File(filePath);
        if (file != null && file.exists()) {
            FileUtils.openFile(file, this);
        } else {
            Intent intent = new Intent();
            intent.putExtra("msgbody", message.getBody());
            intent.setClass(this, ShowNomalFileActivity.class);
            startActivity(intent);
        }
        if (message.direct == EMMessage.Direct.RECEIVE && !message.isAcked) {
            try {
                EMChatManager.getInstance().ackMessageRead(message.getFrom(), message.getMsgId());
                message.isAcked = true;
            } catch (EaseMobException e) {
                e.printStackTrace();
            }
        }


    }

    //点击表情
    @Override
    public void OnRecyclerItemClick(int position) {
        Html.ImageGetter imageGetter = new Html.ImageGetter() {
            @Override
            public Drawable getDrawable(String source) {
                int id = Integer.parseInt(source);
                Drawable drawable = getResources().getDrawable(id);
                drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
                return drawable;
            }
        };
        CharSequence cs = Html.fromHtml("<img src='" + Constant.faces[position] + "'/>", imageGetter, null);
        input_text.getText().append(cs);
    }

    //未添加dialog
    @Override
    public void OnChatOneLongClick(View view, String MsgId) {

    }

    //点击视频
    public void ClickVideoTv() {
        Intent intent = new Intent();
        intent.setClass(this, SendVideoActivity.class);
        startActivityForResult(intent, 4);
    }

    protected void selectFileFromLocal() {
        Intent intent = null;
        if (Build.VERSION.SDK_INT < 19) { //19以后这个api不可用，demo这里简单处理成图库选择图片
            intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("*/*");
            intent.addCategory(Intent.CATEGORY_OPENABLE);

        } else {
            intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        }
        startActivityForResult(intent, 1);
    }


    //开始播放语音
    private void startPlaying(String name) {
        try {
            player = new MediaPlayer();
            player.setDataSource(name);
            player.prepare();
            player.start();
            player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    stopPlaying();
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //停止语音
    private void stopPlaying() {
        if (player != null) {
            player.stop();
            player.release();
            player = null;
        }
    }


    //开始录音
    public void startRecording() {
        try {
            mediaRecorder = new MediaRecorder();
            mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);//设置麦克风
            mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);//设置输出文件
            mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);//设置编码格式
            if (DliaoUtils.isExitsSdcard()) {
                String fileName = System.currentTimeMillis() + ".mp3";
                diaoFile = new File(Environment.getExternalStorageDirectory().getAbsoluteFile() + "/diao");
                if (!diaoFile.exists()) {
                    diaoFile.mkdir();
                }
                diaoFile = new File(Environment.getExternalStorageDirectory().getAbsoluteFile() + "/diao/" + fileName);
                if (!diaoFile.exists()) {
                    diaoFile.createNewFile();
                }
                Log.i("sssddddd", diaoFile.getAbsolutePath() + "   " + fileName);
                mediaRecorder.setOutputFile(diaoFile.getAbsolutePath());
                mediaRecorder.prepare();
                mediaRecorder.start();

                Log.i(" mediaRecorder.start();", "开始录音");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //结束录音
    public void stopRecording() {
        if (mediaRecorder != null) {
            mediaRecorder.setOnErrorListener(null);
            mediaRecorder.setOnInfoListener(null);
            mediaRecorder.stop();
            Log.i("sssssddd", " mediaRecorder.stop();");
            mediaRecorder.release();
            mediaRecorder = null;
            sendVoiceMessage(diaoFile.getAbsolutePath(), (int) diaoFile.getAbsoluteFile().length());
        }
    }


    //点击语音按钮
    private void clickVoice() {
        hideSoftKeyboard();
        recyclerView.setVisibility(View.GONE);
        chatLin.setVisibility(View.GONE);
        face.setImageResource(R.drawable.face);
        if (isVoice) {
            voice.setImageResource(R.drawable.keyboard);
            input_text.setVisibility(View.GONE);
            speak.setVisibility(View.VISIBLE);
            isFace = true;
            isChatLin = true;
        } else {
            voice.setImageResource(R.drawable.voice);
            speak.setVisibility(View.GONE);
            input_text.setVisibility(View.VISIBLE);
            isFace = true;
            isChatLin = true;
        }
        isVoice = !isVoice;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == 3) {
                if (data != null) {
                    Uri selectedImage = data.getData();
                    if (selectedImage != null) {
                        sendPicByUri(selectedImage);
                        handler.postDelayed(runnable, 200);
                    }
                }
            } else if (requestCode == 2) {
                if (cameraFile != null && cameraFile.exists()) {
                    sendImageByCamera(cameraFile.getAbsolutePath());
                    handler.postDelayed(runnable, 200);
                }
            } else if (requestCode == 1) {
                if (data != null) {
                    Uri uri = data.getData();
                    if (uri != null) {
                        sendFileByUri(uri);
                    }
                }
            } else if (requestCode == 4) {
                if (data != null) {
                    int duration = data.getIntExtra("dur", 0);
                    String videoPath = data.getStringExtra("path");
                    Log.i("hjjkkllljjhh", videoPath);
                    File file = new File(PathUtil.getInstance().getImagePath(), "dlvideo" + System.currentTimeMillis());
                    try {
                        FileOutputStream fileOutputStream = new FileOutputStream(file);
                        Bitmap bitmap = ThumbnailUtils.createVideoThumbnail(videoPath,3);
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream);
                        fileOutputStream.close();
                        sendVideoMessage(videoPath, file.getAbsolutePath(), duration);


                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                }
            }else if (requestCode == 520){//位置
                String addr = data.getStringExtra("location");
                if (addr != null && !addr.equals("")){
                    //发送一条文字消息(当前位置)
                    sendLocationMessage(addr);
                }else {
                    Toast.makeText(this, "木有发现你的位置..请重新定位", Toast.LENGTH_SHORT).show();
                }
            }else if (requestCode == 1000){
                String result = data.getStringExtra("result");
                String clear = data.getStringExtra("clear");
                String exit = data.getStringExtra("exit");
                if (result != null && result.equals("确定")){
                    GroupChatActivity.this.finish();
                }
                if (clear != null && clear.equals("清空聊天记录")){
                    handler.postDelayed(runnable, 200);
                }
                if (exit != null && exit.equals("退出群聊")){
                    finish();
                }

            }

        }
    }

    /**
     * 发送当前位置的消息
     * **/
    private void sendLocationMessage(String addr) {
        String content = FilterHtml(addr);
        if (!"".equals(content)) {
            //获取到与聊天人得会话对象.参数username为聊天人的userid活着groupid
            EMConversation conversation = EMChatManager.getInstance().getConversation(groupName);
            //创建一条文本消息
            EMMessage message = EMMessage.createSendMessage(EMMessage.Type.TXT);
            //如果是群聊设置chattype,默认的是单聊
//                    message.setChatType(EMMessage.ChatType.Chat);
            //设置消息body
            TextMessageBody textMessageBody = new TextMessageBody(content);
            message.addBody(textMessageBody);
            //设置接收人
            message.setReceipt(groupName);
            //把消息加入到此会话对象中
            conversation.addMessage(message);

            EMChatManager.getInstance().sendMessage(message, new EMCallBack() {
                @Override
                public void onSuccess() {
                    Log.i("chart", "发送成功");
                }

                @Override
                public void onError(int i, String s) {
                    Log.i("chart", "发送失败");
                }

                @Override
                public void onProgress(int i, String s) {

                }
            });
            input_text.setText("");//清空输入框内容
        }
        handler.postDelayed(runnable, 200);
    }


    private void sendFileByUri(Uri uri) {
        String filePath = null;
        if ("content".equalsIgnoreCase(uri.getScheme())) {
            String[] filePathColumn = {MediaStore.Images.Media.DATA};
            Cursor cursor = null;

            try {
                cursor = this.getContentResolver().query(uri, filePathColumn, null, null, null);
                int column_index = cursor.getColumnIndexOrThrow("_data");
                if (cursor.moveToFirst()) {
                    filePath = cursor.getString(column_index);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
            filePath = uri.getPath();
        }
        File file = new File(filePath);
        if (file == null || !file.exists()) {
            Toast.makeText(this, "文件不存在", Toast.LENGTH_SHORT).show();
            return;
        }
        //大于10M不让发送
        if (file.length() > 10 * 1024 * 1024) {
            Toast.makeText(this, "文件不能大于10", Toast.LENGTH_SHORT).show();
            return;
        }
        sendFileMessage(filePath);
    }


    //相机发送
    private void selectPicFromCamera() {
        if (!DliaoUtils.isExitsSdcard()) {
            Toast.makeText(this, "sd卡不存在", Toast.LENGTH_SHORT).show();
            ;
            return;
        }
        cameraFile = new File(PathUtil.getInstance().getImagePath(), EMChatManager.getInstance().getCurrentUser() + System.currentTimeMillis() + ".jpg");
        cameraFile.getParentFile().mkdirs();
        startActivityForResult(
                new Intent(MediaStore.ACTION_IMAGE_CAPTURE).putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(cameraFile)),
                2);

    }

    //从图册选取照片
    private void selectPicFromLocal() {
        Intent intent;
        if (Build.VERSION.SDK_INT < 19) {
            intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("image/*");
        } else {
            intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        }
        startActivityForResult(intent, 3);//本地相册请求码

    }

    //点击表情
    private void clickFace() {
        hideSoftKeyboard();
        chatLin.setVisibility(View.GONE);
        voice.setImageResource(R.drawable.voice);
        speak.setVisibility(View.GONE);
        input_text.setVisibility(View.VISIBLE);
        if (isFace) {
            face.setImageResource(R.drawable.faced);
            recyclerView.setVisibility(View.VISIBLE);
            isVoice = true;
            isChatLin = true;
        } else {
            face.setImageResource(R.drawable.face);
            recyclerView.setVisibility(View.GONE);
            isVoice = true;
            isChatLin = true;
        }
        isFace = !isFace;
    }

    //点击加号
    private void clickPlus() {
        hideSoftKeyboard();
        face.setImageResource(R.drawable.face);
        if (isChatLin) {
            recyclerView.setVisibility(View.GONE);
            chatLin.setVisibility(View.VISIBLE);
            isVoice = true;
            isFace = true;
        } else {
            chatLin.setVisibility(View.GONE);
            isVoice = true;
            isFace = true;
        }
        isChatLin = !isChatLin;
    }


    //选图片
    private void sendPicByUri(Uri selectedImage) {
        String[] filePathColumn = {MediaStore.Images.Media.DATA};
        Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
        if (cursor != null) {
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String picturePath = cursor.getString(columnIndex);
            cursor.close();
            if (picturePath == null || picturePath.equals("null")) {
                Toast.makeText(this, "找不到图片", Toast.LENGTH_SHORT).show();
                return;
            }
            sendImageMessage(picturePath);
        } else {
            File file = new File(selectedImage.getPath());
            if (!file.exists()) {
                Toast.makeText(this, "找不到图片", Toast.LENGTH_SHORT).show();
                return;
            }
            //大于10M不让发送
            if (file.length() > 10 * 1024 * 1024) {
                Toast.makeText(this, "文件不能大于10M", Toast.LENGTH_SHORT).show();
                return;
            }
            sendImageMessage(file.getAbsolutePath());
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EMChatManager.getInstance().unregisterEventListener(this);
        if (mediaRecorder != null) {
            mediaRecorder.stop();
            mediaRecorder.release();
            mediaRecorder = null;
        }
    }

    ////////////////////////////////////////////////
    //得到消息
    private void sendTxtMessage() {
        text = FilterHtml(Html.toHtml(input_text.getText()));
        ;
        sendTextMessage(text);

    }

    //转化表情
    public String FilterHtml(String str) {
        str = str.replaceAll("<(?!br|img)[^>]+>", "").trim();
        return str;
    }

    //发送文件
    private void sendFileMessage(String filePath) {
        EMMessage message = EMMessage.createFileSendMessage(filePath, groupName);
        sendGroupMessage(message);
    }

    //照相
    private void sendImageByCamera(String absolutePath) {
        EMMessage message = EMMessage.createImageSendMessage(absolutePath, false, groupName);
        sendGroupMessage(message);

    }

    private void sendVideoMessage(String videoPath, String absolutePath, int duration) {
        EMMessage message = EMMessage.createVideoSendMessage(videoPath, absolutePath, duration, groupName);
        sendGroupMessage(message);

    }

    private void sendImageMessage(String picturePath) {
        EMMessage message = EMMessage.createImageSendMessage(picturePath, false, groupName);
        sendGroupMessage(message);
    }


    //发送文字消息
    private void sendTextMessage(String text) {
        EMMessage message = EMMessage.createTxtSendMessage(text, groupName);
        sendGroupMessage(message);


    }

    //发送群消息
    private void sendGroupMessage(EMMessage message) {
        message.setChatType(EMMessage.ChatType.GroupChat);
        EMChatManager.getInstance().sendMessage(message, null);

    }

    protected void sendVoiceMessage(String filePath, int length) {
        EMMessage message = EMMessage.createVoiceSendMessage(filePath, length, groupName);
        sendGroupMessage(message);
    }

    @Override
    public void onEvent(EMNotifierEvent emNotifierEvent) {
        switch (emNotifierEvent.getEvent()) {
            case EventNewMessage:
                handler.postDelayed(runnable, 200);
                break;
        }
    }


    @Override
    public void onShowVideoClick(EMMessage message) {
        VideoMessageBody videoMessageBody = (VideoMessageBody) message.getBody();
        Intent intent = new Intent();
        intent.setClass(this, ShowVideoActivity.class);
        intent.putExtra("localpath", videoMessageBody.getLocalUrl());
        intent.putExtra("secret",videoMessageBody.getSecret());
        intent.putExtra("remotepath", videoMessageBody.getRemoteUrl());
        startActivity(intent);
    }
}
